import type {IQuery, Response, TableResponse} from '@/api/config/types';
import {exportFile, fileUploader} from '@/api/utils/file';
import {message} from 'ant-design-vue';
import {SystemStatus} from '@/global/enum/status.enum';
import axios from 'axios';
import type {MonitorJob} from "./types"
import type {PendingUpdates} from '@/types/system';

/**
 * @description: 统一管理API前缀，方便修改
 */
const REQUEST_PREFIX = 'monitor/job';

/**
 * @description: 查询定时任务调度列表
 * @param {IQuery} query 系统通用查询对象
 */
export const fetchJobList = (query: IQuery) => {
    return axios.get<TableResponse<MonitorJob>>(`${REQUEST_PREFIX}/list`, {
        params: query,
    });
};

/**
 * @description: 查询定时任务调度详细
 * @param {number} jobId 主键ID
 */
export const fetchJobById = (jobId: number | string) => {
    return axios.get<Response<MonitorJob>>(`${REQUEST_PREFIX}/${jobId}`);
};

/**
 * @description: 新增定时任务调度
 * @param {MonitorJob} data 需要添加的数据
 */
export const createJob= (data: MonitorJob) => {
    return axios.post<Response<MonitorJob>>(`${REQUEST_PREFIX}`, data);
};


/**
 * @description: 更新定时任务调度
 * @param {MonitorJob} data 更新数据
 */
export const updateJob = (data: MonitorJob) => {
    return axios.put<Response<MonitorJob>>(`${REQUEST_PREFIX}`, data);
};

/**
 * @description: 删除定时任务调度
 * @param {number[]} jobIds 传入ID数组,可以删除多个
 */
export const deleteJob = (jobIds: (number | string)[]) => {
    return axios.delete<Response<MonitorJob>>(`${REQUEST_PREFIX}/${jobIds.join(',')}`);
};

/**
 * @description: 批量新增定时任务调度
 * @param {MonitorJob[]} list
 */
export const batchCreateJob = (list: MonitorJob[]) => {
    return axios.post<Response>(`${REQUEST_PREFIX}/batch`, list);
};
/**
 * @description: 加载所有定时任务调度
 */
export const loadAllJob = () => {
    return axios.get<TableResponse<MonitorJob>>(`${REQUEST_PREFIX}/loadAll`);
};

/**
 * @description: 导出定时任务调度
 */
export const exportJob = async (query: IQuery) => {
    try {
        await exportFile({
            url: `${REQUEST_PREFIX}/export`,
            data: query,
            fileName: '定时任务调度.xls',
            method: 'POST',
        });
        message.success(`成功下载`);
    } catch (e) {
        message.success(`下载失败`);
    }
};
/**
 * @description: 三向绑定 前端-后端-数据库 定时任务调度
 */
export const updateJobAttr = (config: PendingUpdates) => {
    return axios.post<Response<MonitorJob>>(`${REQUEST_PREFIX}/updateAttr`, {...config});
};

/**
 * @description: 下载模板,用于批量导入测试表
 */
export const importJob = async (file: File) => {
    try {
        const data = {
            file,
            path: file.name,
        };
        const {response} = await fileUploader({
            files: [data],
            url: `${REQUEST_PREFIX}/importData`,
        });
        if (response.code === SystemStatus.SUCCESS) {
            message.success('上传成功');
        }
    } catch (e) {
        message.success(`上传失败`);
    }
};
